#version 430

in vec3 VertPos;
in vec2 TexCoords;
in vec3 N;

// Light information
uniform vec3 LightPosition;				// Light position in eye view
uniform vec3 Ia;						// Ambient intensity
uniform vec3 Id;						// Diffuse and specular light intensity
uniform float MinAttenuation;			// Minimum attenuation for the light (really intense light like sun, moon, etc)

// Object material
uniform vec3 Kd;						// Diffuse reflection coefficient (0 - 1)
uniform vec3 Ka;						// Ambient Reflection Coefficient
uniform vec3 Ks;						// Specular Reflection Coefficient
uniform bool UseDiffuseTexture;			// Check wether to use a texture or not
uniform sampler2D DiffuseTexture;		// Diffuse texture in case one is used

out vec4 FragColour;

void main() {
	//Calculate the light vector
	vec3 LightVector = LightPosition - VertPos;
	vec3 L = normalize(LightVector);  
    
	//Normalize perspective vector
	vec3 V = -normalize(VertPos);

	// Texture color
	vec3 color = vec3(1.0f);

	if (UseDiffuseTexture) { color = texture(DiffuseTexture, TexCoords).rgb; }

	/////////////////////
	//AMBIENT TERM
	/////////////////////
	vec3 AmbientTerm = (Ia * Ka * color);

	/////////////////////
	//DIFFUSE TERM
	/////////////////////
	float A = 1.0f - pow(length(LightVector) / 100.f, 2);
	float Attenuation = max(A, MinAttenuation);
	vec3 DiffuseTerm = Attenuation * color * Kd * max(dot(N,L), 0.0);

	/////////////////////
	//SPECULAR TERM
	/////////////////////
	vec3 R = -reflect(L, N);
	vec3 SpecularTerm = Attenuation * Id * color * Ks * pow(max(dot(R, V), 0.0), 2);
	SpecularTerm = clamp(SpecularTerm, 0.0, 1.0);

	/////////////////////
	//FINAL COLOR
	/////////////////////
	vec3 I = AmbientTerm + DiffuseTerm + SpecularTerm;
	I = clamp(I, 0.0, 1.0);

	FragColour = vec4(I, 1.0);
}
